package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.myexception.MyException;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerService;
import com.dongdongshop.util.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("sellerController")
public class SellerController {

    @DubboReference
    private SellerService sellerService;


    @RequestMapping("checkName")
    @ResponseBody
    public Result checkName(String sellerId) {
        try {
            Boolean b = sellerService.checkName(sellerId);
            return Result.ok().setData(b);
        }catch (Exception e) {
            return Result.respones(ResultEnum.ERROR);
        }
    }

    @RequestMapping("toRegister")
    @ResponseBody
    public Result toRegister(TbSeller tbSeller) {
        try {
            String password = tbSeller.getPassword();
            tbSeller.setSalt(ShiroUtils.generateSalt(6));
            tbSeller.setPassword(ShiroUtils.encryptPassword("MD5", password, tbSeller.getSalt(), 10));
            sellerService.toRegister(tbSeller);
            return Result.respones(ResultEnum.SUCCESS);
        }catch (Exception e) {
            return Result.respones(ResultEnum.ERROR);
        }
    }

    @RequestMapping("login")
    @ResponseBody
    public Result login(String sellerId, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sellerId,password);
        try {
            subject.login(token);
        }catch (UnknownAccountException u) {
            return Result.respones(ResultEnum.ERROR).setData("用户不存在");
        }catch (IncorrectCredentialsException i) {
            return Result.respones(ResultEnum.ERROR).setData("密码错误");
        }catch (MyException m) {
            return Result.respones(ResultEnum.ERROR).setData(m.getMessage());
        }
        return Result.respones(ResultEnum.SUCCESS).setData("登录成功");
    }
}
